import { defineStore } from 'pinia'
import type { iState, iItem} from '@/interfaces/interfaceTodo'


// useTodoStore
export const useTodoStore = defineStore('todoStore', {
  persist: true,  // 数据持久化
  // 数据
  state: (): iState => {
    return {
      value: '' as string,  // 要添加的待办事项
      list: [] as iItem[]  // 已添加的待办事项
    }
  },
  actions: {
    // 添加待办项
    addTodoItem() {
      if(!this.value) {
        alert('请输入待办事项')
        return
      }
      this.list.unshift({
        id: Math.floor(Math.random() * 100000000).toString() + '',
        value: this.value,
        checked: false
      })
      this.value = ""
    },
    // 更新待办事项
    updateItem(id:string, newItem:iItem) {
      console.log(id, newItem);
      console.log(this.list, newItem);
      
      this.list.map(item => {
        if(item.id === id) {
          item.value = newItem.value
          item.checked = newItem.checked
        }
      })
    },
    // 删除待办项
    delTodoItem(id: string) {
      let fIndex = this.list.findIndex(item => item.id === id)
      if(fIndex != -1) {
        this.list.splice(fIndex, 1)
      }
    },
    // 选择待办项
    checkTodo(checked: boolean, id: string) {
      this.list.forEach(item => {
        if(item.id === id) item.checked = checked
      })
    }
  }
})



